/**
 * Copyright (c) 2015 - present LibDriver All rights reserved
 * 
 * The MIT License (MIT)
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE. 
 *
 * @file      uart.c
 * @brief     uart源文件
 * @version   1.0.0
 * @author    Shifeng Li
 * @date      2022-11-11
 *
 * <h3>历史</h3>
 * <table>
 * <tr><th>日期        <th>版本  <th>作者      <th>描述
 * <tr><td>2022/11/11  <td>1.0      <td>Shifeng Li  <td>首次上传
 * </table>
 */

#include "uart.h"
#include <stdarg.h>
#include <stdio.h>
#include <string.h>

/**
 * @brief uart1 变量定义
 */
UART_HandleTypeDef g_uart_handle;              /**< uart句柄 */
uint8_t g_uart_rx_buffer[UART_MAX_LEN];        /**< uart接收缓冲区 */
uint8_t g_uart_buffer;                         /**< uart单字节缓冲区 */
volatile uint16_t g_uart_point;                /**< uart接收指针 */
volatile uint8_t g_uart_tx_done;               /**< uart发送完成标志 */

/**
 * @brief uart2 变量定义
 */
UART_HandleTypeDef g_uart2_handle;               /**< uart2句柄 */
uint8_t g_uart2_rx_buffer[UART2_MAX_LEN];        /**< uart2接收缓冲区 */
uint8_t g_uart2_buffer;                          /**< uart2单字节缓冲区 */
volatile uint16_t g_uart2_point;                 /**< uart2接收指针 */
volatile uint8_t g_uart2_tx_done;                /**< uart2发送完成标志 */

/**
 * @brief     uart初始化
 * @param[in] baud 波特率
 * @return    状态码
 *            - 0 成功
 *            - 1 初始化失败
 * @note      TX是PA9，RX是PA10
 */
uint8_t uart_init(uint32_t baud)
{
    g_uart_handle.Instance = USART1;
    g_uart_handle.Init.BaudRate = baud;
    g_uart_handle.Init.WordLength = UART_WORDLENGTH_8B;
    g_uart_handle.Init.StopBits = UART_STOPBITS_1;
    g_uart_handle.Init.Parity = UART_PARITY_NONE;
    g_uart_handle.Init.Mode = UART_MODE_TX_RX;
    g_uart_handle.Init.HwFlowCtl = UART_HWCONTROL_NONE;
    g_uart_handle.Init.OverSampling = UART_OVERSAMPLING_16;
    
    /* uart初始化 */
    if (HAL_UART_Init(&g_uart_handle) != HAL_OK)
    {
        return 1;
    }
    
    /* 接收一个字节 */
    if (HAL_UART_Receive_IT(&g_uart_handle, (uint8_t *)&g_uart_buffer, 1) != HAL_OK)
    {
        return 1;
    }
    
    return 0;
}

/**
 * @brief  uart反初始化
 * @return 状态码
 *         - 0 成功
 *         - 1 反初始化失败
 * @note   无
 */
uint8_t uart_deinit(void)
{
    /* uart反初始化 */
    if (HAL_UART_DeInit(&g_uart_handle) != HAL_OK)
    {
        return 1;
    }
    
    return 0;
}

/**
 * @brief     uart写数据
 * @param[in] *buf 数据缓冲区指针
 * @param[in] len 数据长度
 * @return    状态码
 *            - 0 成功
 *            - 1 写入失败
 * @note      无
 */
uint8_t uart_write(uint8_t *buf, uint16_t len)
{
    uint16_t timeout = 1000;
    
    /* 设置发送完成标志为0 */
    g_uart_tx_done = 0;
    
    /* 发送数据 */
    if (HAL_UART_Transmit_IT(&g_uart_handle, (uint8_t *)buf, len) != HAL_OK)
    {
        return 1;
    }
    
    /* 等待事件 */
    while ((g_uart_tx_done == 0) && (timeout != 0))
    {
        HAL_Delay(1);
        timeout--;
    }
    
    /* 检查超时 */
    if (timeout != 0)
    {
        return 0;
    }
    else
    {
        return 1;
    }
}

/**
 * @brief      uart读数据
 * @param[out] *buf 数据缓冲区指针
 * @param[in]  len 数据长度
 * @return     读取的数据长度
 * @note       即使读取长度小于接收长度，此函数也会清除所有接收缓冲区
 */
uint16_t uart_read(uint8_t *buf, uint16_t len)
{
    uint16_t read_len;
    uint16_t g_uart_point_old;
    
    /* 检查接收状态 */
    start:
    g_uart_point_old = g_uart_point;
    HAL_Delay(1);
    if (g_uart_point > g_uart_point_old)
    {
        goto start;
    }
    
    /* 复制数据 */
    read_len = (len < g_uart_point) ? len : g_uart_point;
    memcpy(buf, g_uart_rx_buffer, read_len);
    
    /* 清除缓冲区 */
    g_uart_point = 0;
    
    return read_len;
}

/**
 * @brief  uart清空数据
 * @return 状态码
 *         - 0 成功
 * @note   无
 */
uint16_t uart_flush(void)
{
    /* 清除缓冲区 */
    g_uart_point = 0;
    
    return 0;
}

/**
 * @brief     uart打印格式化数据
 * @param[in] fmt 格式化数据
 * @return    发送的数据长度
 * @note      无
 */
uint16_t uart_print(const char *const fmt, ...)
{
    char str[256];
    uint16_t len;
    va_list args;
    
    /* 打印到缓冲区 */
    memset((char *)str, 0, sizeof(char) * 256); 
    va_start(args, fmt);
    vsnprintf((char *)str, 255, (char const *)fmt, args);
    va_end(args);
    
    /* 发送数据 */
    len = strlen((char *)str);
    if (uart_write((uint8_t *)str, len) != 0)
    {
        return 0;
    }
    else
    { 
        return len;
    }
}

/**
 * @brief     uart2初始化，8位数据位，1位停止位，无校验位
 * @param[in] baud 波特率
 * @return    状态码
 *            - 0 成功
 *            - 1 初始化失败
 * @note      TX是PA2，RX是PA3
 */
uint8_t uart2_init(uint32_t baud)
{
    g_uart2_handle.Instance = USART2;
    g_uart2_handle.Init.BaudRate = baud;
    g_uart2_handle.Init.WordLength = UART_WORDLENGTH_8B;
    g_uart2_handle.Init.StopBits = UART_STOPBITS_1;
    g_uart2_handle.Init.Parity = UART_PARITY_NONE;
    g_uart2_handle.Init.Mode = UART_MODE_TX_RX;
    g_uart2_handle.Init.HwFlowCtl = UART_HWCONTROL_NONE;
    g_uart2_handle.Init.OverSampling = UART_OVERSAMPLING_16;
    
    /* uart初始化 */
    if (HAL_UART_Init(&g_uart2_handle) != HAL_OK)
    {
        return 1;
    }
    
    /* 接收一个字节 */
    if (HAL_UART_Receive_IT(&g_uart2_handle, (uint8_t *)&g_uart2_buffer, 1) != HAL_OK)
    {
        return 1;
    }
    
    return 0;
}

/**
 * @brief  uart2反初始化
 * @return 状态码
 *         - 0 成功
 *         - 1 反初始化失败
 * @note   无
 */
uint8_t uart2_deinit(void)
{
    /* uart反初始化 */
    if (HAL_UART_DeInit(&g_uart2_handle) != HAL_OK)
    {
        return 1;
    }
    
    return 0;
}

/**
 * @brief     uart2写数据
 * @param[in] *buf 数据缓冲区指针
 * @param[in] len 数据长度
 * @return    状态码
 *            - 0 成功
 *            - 1 写入失败
 * @note      无
 */
uint8_t uart2_write(uint8_t *buf, uint16_t len)
{
    uint16_t timeout = 1000;
    
    /* 设置发送完成标志为0 */
    g_uart2_tx_done = 0;
    
    /* 发送数据 */
    if (HAL_UART_Transmit_IT(&g_uart2_handle, (uint8_t *)buf, len) != HAL_OK)
    {
        return 1;
    }
    
    /* 等待事件 */
    while ((g_uart2_tx_done == 0) && (timeout != 0))
    {
        HAL_Delay(1);
        timeout--;
    }
    
    /* 检查超时 */
    if (timeout != 0)
    {
        return 0;
    }
    else
    {
        return 1;
    }
}

/**
 * @brief      uart2读数据
 * @param[out] *buf 数据缓冲区指针
 * @param[in]  len 数据长度
 * @return     读取的数据长度
 * @note       即使读取长度小于接收长度，此函数也会清除所有接收缓冲区
 */
uint16_t uart2_read(uint8_t *buf, uint16_t len)
{
    uint16_t read_len;
    uint16_t g_uart_point_old;
    
    /* 检查接收状态 */
    start:
    g_uart_point_old = g_uart2_point;
    HAL_Delay(1);
    if (g_uart2_point > g_uart_point_old)
    {
        goto start;
    }
    
    /* 复制数据 */
    read_len = (len < g_uart2_point) ? len : g_uart2_point;
    memcpy(buf, g_uart2_rx_buffer, read_len);
    
    /* 清除缓冲区 */
    g_uart2_point = 0;
    
    return read_len;
}

/**
 * @brief  uart2清空数据
 * @return 状态码
 *         - 0 成功
 * @note   无
 */
uint16_t uart2_flush(void)
{
    /* 清除缓冲区 */
    g_uart2_point = 0;
    
    return 0;
}

/**
 * @brief  uart获取句柄
 * @return 指向uart句柄的指针
 * @note   无
 */
UART_HandleTypeDef* uart_get_handle(void)
{
    return &g_uart_handle;
}

/**
 * @brief  uart2获取句柄
 * @return 指向uart句柄的指针
 * @note   无
 */
UART_HandleTypeDef* uart2_get_handle(void)
{
    return &g_uart2_handle;
}

/**
 * @brief uart设置发送完成标志
 * @note  none
 */
void uart_set_tx_done(void)
{
    g_uart_tx_done = 1;
}

/**
 * @brief uart2设置发送完成标志
 * @note  none
 */
void uart2_set_tx_done(void)
{
    g_uart2_tx_done = 1;
}

/**
 * @brief uart中断处理
 * @note  none
 */
void uart_irq_handler(void)
{
    /* save one byte */
    g_uart_rx_buffer[g_uart_point] = g_uart_buffer;
    g_uart_point++;
    if (g_uart_point > (UART_MAX_LEN - 1))
    {
        g_uart_point = 0;
    }
    
    /* receive one byte */
    (void)HAL_UART_Receive_IT(&g_uart_handle, (uint8_t *)&g_uart_buffer, 1);
}

/**
 * @brief uart2中断处理
 * @note  none
 */
void uart2_irq_handler(void)
{
    /* save one byte */
    g_uart2_rx_buffer[g_uart2_point] = g_uart2_buffer;
    g_uart2_point++;
    if (g_uart2_point > (UART2_MAX_LEN - 1))
    {
        g_uart2_point = 0;
    }
    
    /* receive one byte */
    (void)HAL_UART_Receive_IT(&g_uart2_handle, (uint8_t *)&g_uart2_buffer, 1);
}
